package com.tj.admin.auth.service;

import com.aliyun.openservices.shade.io.netty.util.internal.StringUtil;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.exception.common.ApplicationException;
import com.google.common.collect.Lists;
import com.tj.admin.auth.config.ApolloConfigUtil;
import com.tj.admin.auth.enums.PictureRestErrorEnum;
import com.tj.admin.auth.response.UploadDTO;
import com.tj.admin.auth.vo.RequestLocalInfo;
import com.tj.admin.auth.vo.UploadInfoVo;
import com.tj.admin.db.dao.AdminTokenDao;
import com.tj.admin.db.dao.UploadDetailDao;
import com.tj.admin.db.entity.AdminTokenEntity;
import com.tj.admin.db.entity.UploadDetailEntity;
import com.tj.bo.common.conf.api.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UploadApplication {
    private final static Logger LOGGER = LoggerFactory.getLogger(UploadApplication.class);

    @Autowired
    private AdminTokenDao adminTokenDao;
    @Autowired
    private UploadDetailDao uploadDetailDao;

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    @Autowired
    private OSSService ossService;

    public String uploadExcel(HttpServletRequest request) {
        AdminTokenEntity adminTokenEntity = adminTokenDao.selectOnByAccessToken(RequestLocalInfo.getCurrentUser().getAccessToken());
        String merchantCode = adminTokenEntity.getMerchantCode();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");
        LOGGER.info("=== 开始上传2211 userCode:{},size:{}===",multipartFile.getOriginalFilename(), multipartFile.getSize());
        if (!multipartFile.getOriginalFilename().contains(".xlsx")){
            throw new ApplicationException(PictureRestErrorEnum.PICTURE_NULL);
        }
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new ApplicationException(PictureRestErrorEnum.PICTURE_NULL);
        }

        if (multipartFile.getSize() > 10000000) {
            throw new ApplicationException(PictureRestErrorEnum.PICTURE_OVER_SIZE);
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = apolloConfigUtil.isServerTest() ? "excel/test/" + merchantCode + "/" + uuid : "excel/" + merchantCode + "/" + uuid + "_B"+".xlsx";
        ByteArrayOutputStream outputStream = null;
        InputStream in1 = null;
//        InputStream in2 = null;
        try {
            InputStream inputStream = multipartFile.getInputStream();
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            in1 = new ByteArrayInputStream(outputStream.toByteArray());
            ossService.uploadFile(apolloConfigUtil.getBucketName(), in1, multipartFile.getSize(), fileName);
            LOGGER.info("上传成功:{},url:{}", fileName, apolloConfigUtil.getOssBaseUrl() + fileName);
        } catch (Exception e) {
            LOGGER.error("上传失败，userCode:" + merchantCode + ",exception:" + e);
            throw new ApplicationException(PictureRestErrorEnum.PICTURE_UPLOAD);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (in1 != null) {
                    in1.close();
                }
//                if (in2 != null) {
//                    in2.close();
//                }
            } catch (IOException var15) {
            }
        }
        return apolloConfigUtil.getOssBaseUrl() + fileName;
    }

    public Boolean saveFileInfo(String url,String content){
        if (StringUtil.isNullOrEmpty(url)){
            throw new RuntimeException("File can't be empty");
        }
        if (StringUtil.isNullOrEmpty(content)){
            throw new RuntimeException("Note can't be empty");
        }
        AdminTokenEntity adminTokenEntity = adminTokenDao.selectOnByAccessToken(RequestLocalInfo.getCurrentUser().getAccessToken());
        String merchantCode = adminTokenEntity.getMerchantCode();
        UploadDetailEntity detail = new UploadDetailEntity();
        detail.setMerchantCode(merchantCode);
        detail.setContent(content);
        detail.setUploadDate(new Date());
        detail.setUploadStatus(0);
        detail.setUploadUrl(url);
        detail.setUploadStatusText("success");
        uploadDetailDao.insert(detail);
        return true;
    }


    public ApiResponse<UploadDTO> selectUploadInfoList(Page page){
        AdminTokenEntity adminTokenEntity = adminTokenDao.selectOnByAccessToken(RequestLocalInfo.getCurrentUser().getAccessToken());
        String merchantCode = adminTokenEntity.getMerchantCode();
        List<UploadDetailEntity> uploadDetailEntities = uploadDetailDao.selectListByPage(page,merchantCode);
        ArrayList<UploadInfoVo> list = Lists.newArrayList();
        uploadDetailEntities.forEach(uploadDetailEntity -> {
            UploadInfoVo infoVo = new UploadInfoVo();
            infoVo.setId(uploadDetailEntity.getId());
            infoVo.setDate(DateUtil.getDate(uploadDetailEntity.getUploadDate(),"yyyy-MM-dd HH:mm:ss"));
            infoVo.setNote(uploadDetailEntity.getContent());
            infoVo.setStatus(uploadDetailEntity.getUploadStatus() == 0?"Success":"Fail");
            infoVo.setExplain(uploadDetailEntity.getUploadStatusText());
            list.add(infoVo);
        });
        UploadDTO uploadDTO = new UploadDTO();
        uploadDTO.setList(CollectionUtils.isEmpty(list) ? Lists.newArrayList(): list);
        Integer count = uploadDetailDao.selectListCount(merchantCode);
        page.setTotalCount(count);
        return new ApiResponse<>(uploadDTO).setPage(page);
    }

    public ApiResponse<UploadDTO> selectUploadInComeList(){


        return null;
    }
}
